<template>
	<view class="withdraw-records-page">
		<!-- 自定义头部 -->
		<headerSlot :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header-container">
					<view class="back-btn" @click="closePage()">
						<text class="cuIcon-back"></text>
					</view>
					<view class="page-title">
						提现记录
					</view>
					<view class="subscribe-btn" @click="showSubscribeOptions">
						<text class="cuIcon-notification"></text>
					</view>
				</view>
			</template>
		</headerSlot>

		<!-- 主要内容区域 -->
		<view class="content-container">
			<!-- 统计卡片 -->
			<view class="stats-card">
				<view class="stats-item">
					<view class="stats-value">{{stats.totalAmount}}</view>
					<view class="stats-label">累计提现</view>
				</view>
				<view class="stats-item">
					<view class="stats-value">{{stats.successAmount}}</view>
					<view class="stats-label">成功到账</view>
				</view>
				<view class="stats-item">
					<view class="stats-value">{{stats.totalCount}}</view>
					<view class="stats-label">提现次数</view>
				</view>
			</view>

			<!-- 筛选栏 -->
			<view class="filter-bar">
				<view class="filter-item" :class="{ active: currentStatus === '' }" @click="filterByStatus('')">
					全部
				</view>
				<view class="filter-item" :class="{ active: currentStatus === 'pending' }"
					@click="filterByStatus('pending')">
					待审核
				</view>
				<view class="filter-item" :class="{ active: currentStatus === 'processing' }"
					@click="filterByStatus('processing')">
					处理中
				</view>
				<view class="filter-item" :class="{ active: currentStatus === 'success' }"
					@click="filterByStatus('success')">
					成功
				</view>
				<view class="filter-item" :class="{ active: currentStatus === 'failed' }"
					@click="filterByStatus('failed')">
					失败
				</view>
			</view>

			<!-- 记录列表 -->
			<view class="records-list">
				<view class="record-item" v-for="record in recordsList" :key="record._id"
					@click="viewRecordDetail(record)">
					<view class="record-header">
						<view class="record-amount">
							<text class="currency">￥</text>
							<text class="amount">{{record.amount}}</text>
						</view>
						<view class="record-status"
							:class="statusClassMap[record.status || record.auditStatus || 'pending']">
							{{statusTextMap[record.status || record.auditStatus || 'pending']}}
						</view>
					</view>

					<view class="record-info">
						<view class="info-row">
							<text class="info-label">提现方式：</text>
							<text
								class="info-value">{{record.withdrawMethod === 'bank' && record.accountInfo && record.accountInfo.bankName ? record.accountInfo.bankName : (withdrawMethodMap[record.withdrawMethod] || '未知方式')}}</text>
						</view>
						<view class="info-row">
							<text class="info-label">手续费：</text>
							<text class="info-value">￥{{record.fee}}</text>
						</view>
						<view class="info-row">
							<text class="info-label">实际到账：</text>
							<text class="info-value">￥{{record.actualAmount}}</text>
						</view>
						<view class="info-row">
							<text class="info-label">申请时间：</text>
							<text class="info-value">{{formatDate(record.appliedAt || record.createdAt)}}</text>
						</view>
						<view class="info-row" v-if="record.processInfo && record.processInfo.processTime">
							<text class="info-label">处理时间：</text>
							<text class="info-value">{{formatDate(record.processInfo.processTime)}}</text>
						</view>
					</view>

					<!-- <view class="record-actions" v-if="record.status === 'failed' || record.auditStatus === 'rejected'">
						<button class="retry-btn" @click.stop="retryWithdraw(record)">
							重新申请
						</button>
					</view> -->
				</view>
			</view>

			<!-- 空状态 -->
			<view v-if="recordsList.length === 0 && !loading" class="empty-state">
				<view class="empty-icon">
					<text class="cuIcon-form"></text>
				</view>
				<view class="empty-text">暂无提现记录</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="hasMore && recordsList.length > 0" class="load-more">
				<button class="load-more-btn" :disabled="loading" @click="loadMore">
					<text v-if="loading">加载中...</text>
					<text v-else>加载更多</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import headerSlot from '@/components/header-slot.vue';
	import {
		getWithdrawList,
		getWithdrawStats,
		retryWithdraw,
		getUnconfirmedWithdrawals,
		batchConfirmWithdrawReceipt
	} from '@/api/withdraw.js';
	import Storage from '@/utils/storage.js';
	import {
		subscribeWithdrawMessages,
		openSubscriptionSettings
	} from '@/utils/wechat-subscription.js';
	import modalManager, {
		MODAL_KEYS
	} from "@/utils/modalManager.js";

	export default {
		components: {
			headerSlot,
		},
		data() {
			return {
				loading: false,
				recordsList: [],
				currentStatus: '',
				currentPage: 1,
				pageSize: 10,
				hasMore: true,
				stats: {
					totalAmount: '0.00',
					successAmount: '0.00',
					totalCount: 0
				},
				statusClassMap: {
					pending: 'status-pending',
					processing: 'status-processing',
					success: 'status-success',
					failed: 'status-failed',
					approved: 'status-processing',
					rejected: 'status-failed'
				},
				statusTextMap: {
					pending: '待审核',
					processing: '处理中',
					success: '成功',
					failed: '失败',
					approved: '已审核',
					rejected: '已拒绝'
				},
				withdrawMethodMap: {
					wechat: '微信零钱',
					alipay: '支付宝',
					bank: '银行卡'
				}
			};
		},
		onLoad() {
			this.loadStats()
			this.loadRecords()
		},
		onShow() {
			// 检查是否有未确认收款的提现记录
			this.checkUnconfirmedWithdrawals()
			
			// 检查是否需要刷新数据（从提现页面返回时）
			this.checkAndRefreshData()
		},
		onPullDownRefresh() {
			this.refresh()
		},
		onReachBottom() {
			if (this.hasMore && !this.loading) {
				this.loadMore()
			}
		},
		methods: {
			closePage() {
				uni.navigateBack()
			},

			// 检查并刷新数据
			checkAndRefreshData() {
				// 检查是否有提现成功标志
				const withdrawSuccessTime = uni.getStorageSync('withdrawSuccess');
				if (withdrawSuccessTime) {
		
					this.refresh();
					// 清除提现成功标志
					uni.removeStorageSync('withdrawSuccess');
					return;
				}
				
				// 获取当前时间戳
				const currentTime = Date.now();
				// 获取上次刷新时间
				const lastRefreshTime = uni.getStorageSync('withdrawRecordsLastRefresh') || 0;
				
				// 如果距离上次刷新超过30秒，则刷新数据
				// 这样可以确保从提现页面返回时能及时更新状态
				if (currentTime - lastRefreshTime > 30000) {
		
					this.refresh();
					// 更新刷新时间
					uni.setStorageSync('withdrawRecordsLastRefresh', currentTime);
				}
			},

			// 显示订阅选项
			showSubscribeOptions() {
				uni.showActionSheet({
					itemList: ['订阅提现进度推送', '打开推送设置'],
					success: (res) => {
						if (res.tapIndex === 0) {
							this.subscribeWithdrawProgress()
						} else if (res.tapIndex === 1) {
							openSubscriptionSettings()
						}
					}
				})
			},

			// 订阅提现进度推送
			async subscribeWithdrawProgress() {
				try {
					const result = await subscribeWithdrawMessages()

					if (result.success) {
						if (result.hasAccepted) {
							uni.showToast({
								title: '已开启提现进度推送',
								icon: 'success'
							})
						} else if (result.hasRejected) {
							uni.showToast({
								title: '您已拒绝推送通知',
								icon: 'none'
							})
						} else if (result.hasBanned) {
							uni.showToast({
								title: '订阅消息功能被禁用',
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: result.message || '订阅失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('订阅失败:', error)
					uni.showToast({
						title: '订阅失败',
						icon: 'none'
					})
				}
			},

			// 加载统计数据
			async loadStats() {
				try {
					const response = await getWithdrawStats()
	

					const {
						counts,
						amounts
					} = response.data.data

					this.stats = {
						totalAmount: this.formatAmount(amounts?.totalAmount || 0),
						successAmount: this.formatAmount(amounts?.successAmount || 0),
						totalCount: counts?.total || 0
					}
				} catch (error) {
					console.error('获取统计数据失败:', error)
				}
			},

			// 检查未确认收款的提现记录
			async checkUnconfirmedWithdrawals() {
				try {
					const response = await getUnconfirmedWithdrawals()
					if (response.data.success && response.data.data && response.data.data.length > 0) {
						// 显示未确认收款提醒
						this.showUnconfirmedReminder(response.data)
					}
				} catch (error) {
					console.error('检查未确认收款记录失败:', error)
				}
			},

			// 显示未确认收款提醒
			showUnconfirmedReminder(withdrawals) {
				// 检查是否已经显示过弹窗
				if (!modalManager.checkAndSetModalState(MODAL_KEYS.WITHDRAW_RECORDS_REMINDER, 'daily')) {
		
					return;
				}

				const count = withdrawals.length
				const totalAmount = withdrawals.reduce((sum, item) => sum + parseFloat(item.amount), 0)

				uni.showModal({
					title: '未确认收款提醒',
					content: `您有 ${count} 笔提现转账等待确认收款，总金额：${totalAmount.toFixed(2)}元\n是否立即确认？`,
					confirmText: '立即确认',
					cancelText: '稍后确认',
					success: async (res) => {
						if (res.confirm) {
							await this.batchConfirmReceipt(withdrawals)
						}
					}
				})
			},

			// 批量确认收款
			async batchConfirmReceipt(withdrawals) {
				try {
					uni.showLoading({
						title: '处理中...'
					})

					const withdrawIds = withdrawals.map(item => item._id || item.withdrawId)
					const response = await batchConfirmWithdrawReceipt(withdrawIds)

					uni.hideLoading()

					if (response.success) {
						uni.showToast({
							title: '批量确认收款成功',
							icon: 'success'
						})
						// 刷新记录列表
						this.refresh()
					} else {
						uni.showToast({
							title: response.message || '批量确认收款失败',
							icon: 'none'
						})
					}
				} catch (error) {
					console.error('批量确认收款失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '批量确认收款失败',
						icon: 'none'
					})
				}
			},

			// 加载提现记录
			async loadRecords(refresh = false) {
				if (this.loading) return

				try {
					this.loading = true

					if (refresh) {
						this.currentPage = 1
						this.recordsList = []
						this.hasMore = true
					}

					const params = {
						page: this.currentPage,
						limit: this.pageSize
					}

					if (this.currentStatus) {
						params.status = this.currentStatus
					}

					const response = await getWithdrawList(params)

					if (response.statusCode === 200) {
						const newRecords = response.data.data.list || []

						if (refresh) {
							this.recordsList = newRecords
						} else {
							this.recordsList = [...this.recordsList, ...newRecords]
						}

						// 根据分页信息判断是否还有更多数据
						const pagination = response.data.pagination
						this.hasMore = pagination && pagination.page < pagination.pages
						this.currentPage++
					}
				} catch (error) {
					console.error('获取提现记录失败:', error)
					uni.showToast({
						title: '获取记录失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					uni.stopPullDownRefresh()
				}
			},

			// 筛选状态
			filterByStatus(status) {
				if (this.currentStatus === status) return

				this.currentStatus = status
				this.loadRecords(true)
			},

			// 加载更多
			loadMore() {
				this.loadRecords()
			},

			// 刷新
			refresh() {
				this.loadStats()
				this.loadRecords(true)
			},

			// 查看记录详情
			viewRecordDetail(record) {
				this.$router.smartNavigate({
					url: `/pages/mePages/balance/WithdrawDetail?id=${record._id}`
				})
			},

			// 重新申请提现
			async retryWithdraw(record) {
				try {
					uni.showModal({
						title: '重新申请',
						content: '确定要重新申请这笔提现吗？',
						success: async (res) => {
							if (res.confirm) {
								uni.showLoading({
									title: '处理中...'
								})

								const response = await retryWithdraw(record._id)

								uni.hideLoading()

								if (response.success) {
									uni.showToast({
										title: '重新申请成功',
										icon: 'success'
									})
									// 刷新列表
									this.refresh()
								} else {
									uni.showToast({
										title: response.message || '重新申请失败',
										icon: 'none'
									})
								}
							}
						}
					})
				} catch (error) {
					console.error('重新申请失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: '重新申请失败',
						icon: 'none'
					})
				}
			},



			// 格式化金额
			formatAmount(amount) {
				if (!amount && amount !== 0) return '0.00'
				return Number(amount).toFixed(2)
			},

			// 格式化日期
			formatDate(dateString) {
				if (!dateString) return ''
				const date = new Date(dateString)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				const hours = String(date.getHours()).padStart(2, '0')
				const minutes = String(date.getMinutes()).padStart(2, '0')
				return `${year}-${month}-${day} ${hours}:${minutes}`
			},






		}
	}
</script>

<style lang="scss" scoped>
	.withdraw-records-page {
		min-height: 100vh;
		background: #f5f7fa;
	}

	.header-container {
		display: flex;
		align-items: center;
		padding: 0 32rpx;
		width: 100%;
		height: 88rpx;

		.back-btn {
			margin-right: 20rpx;
			padding: 8rpx;

			.cuIcon-back {
				font-size: 36rpx;
				color: #2C2622;
			}
		}

		.page-title {
			flex: 1;
			font-weight: 600;
			font-size: 36rpx;
			color: #2C2622;
			text-align: center;
		}

		.subscribe-btn {
			padding: 8rpx;

			.cuIcon-notification {
				font-size: 36rpx;
				color: #2C2622;
			}
		}
	}

	.content-container {
		padding: 32rpx;
	}

	.stats-card {
		background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
		border-radius: 20rpx;
		padding: 32rpx 24rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(254, 97, 0, 0.3);
		display: flex;
		justify-content: space-between;

		.stats-item {
			text-align: center;
			flex: 1;

			.stats-value {
				font-size: 36rpx;
				color: #FFFFFF;
				font-weight: 700;
				margin-bottom: 8rpx;
			}

			.stats-label {
				font-size: 24rpx;
				color: rgba(255, 255, 255, 0.9);
			}
		}
	}

	.filter-bar {
		background: #FFFFFF;
		border-radius: 16rpx;
		padding: 16rpx;
		margin-bottom: 32rpx;
		display: flex;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

		.filter-item {
			flex: 1;
			text-align: center;
			padding: 16rpx 8rpx;
			font-size: 28rpx;
			color: #606266;
			border-radius: 12rpx;
			transition: all 0.2s;

			&.active {
				background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
				color: #FFFFFF;
			}
		}
	}

	.records-list {
		.record-item {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 32rpx 24rpx;
			margin-bottom: 24rpx;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

			.record-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 24rpx;

				.record-amount {
					display: flex;
					align-items: baseline;

					.currency {
						font-size: 32rpx;
						color: #2C2622;
						font-weight: 600;
					}

					.amount {
						font-size: 48rpx;
						color: #2C2622;
						font-weight: 700;
					}
				}

				.record-status {
					padding: 8rpx 16rpx;
					border-radius: 12rpx;
					font-size: 24rpx;
					font-weight: 600;

					&.status-pending {
						background: #fff7e6;
						color: #fa8c16;
					}

					&.status-processing {
						background: #e6f7ff;
						color: #1890ff;
					}

					&.status-success {
						background: #f6ffed;
						color: #52c41a;
					}

					&.status-failed {
						background: #fff2f0;
						color: #ff4d4f;
					}
				}
			}

			.record-info {
				.info-row {
					display: flex;
					justify-content: space-between;
					margin-bottom: 12rpx;

					&:last-child {
						margin-bottom: 0;
					}

					.info-label {
						font-size: 28rpx;
						color: #909399;
					}

					.info-value {
						font-size: 28rpx;
						color: #2C2622;
					}
				}
			}

			.record-actions {
				margin-top: 24rpx;
				padding-top: 24rpx;
				border-top: 1rpx solid #f0f0f0;

				.retry-btn {
					width: 100%;
					height: 72rpx;
					background: linear-gradient(135deg, #FE6100 0%, #FF6B35 100%);
					color: #FFFFFF;
					border-radius: 16rpx;
					font-size: 28rpx;
					font-weight: 600;
					display: flex;
					align-items: center;
					justify-content: center;

					&:active {
						transform: scale(0.98);
					}
				}
			}
		}
	}

	.empty-state {
		text-align: center;
		padding: 120rpx 0;

		.empty-icon {
			margin-bottom: 32rpx;

			.cuIcon-form {
				font-size: 120rpx;
				color: #c0c4cc;
			}
		}

		.empty-text {
			font-size: 32rpx;
			color: #909399;
		}
	}

	.load-more {
		text-align: center;
		padding: 32rpx 0;

		.load-more-btn {
			background: #f8f9fa;
			color: #606266;
			border: 2rpx solid #e9ecef;
			border-radius: 16rpx;
			padding: 20rpx 48rpx;
			font-size: 28rpx;

			&:disabled {
				opacity: 0.6;
			}
		}
	}
</style>